const Order = require('../models/Order');
const { Op } = require('sequelize');

const getAllOrders = async (params) => {
    try {
        const where = {};
        let page = 1;
        let pageSize = 10;

        if (params) {
            // 订单号搜索
            if (params.order_no) {
                where.order_no = {
                    [Op.like]: `%${params.order_no}%`
                };
            }

            // 订单状态搜索
            if (params.order_status !== undefined && params.order_status !== '') {
                where.order_status = params.order_status;
            }

            // 租赁日期范围搜索
            if (params.rent_start_date && params.rent_start_date.length === 2) {
                const [startDate, endDate] = params.rent_start_date;
                where.rent_start_date = {
                    [Op.between]: [
                        Math.floor(new Date(startDate).getTime() / 1000),
                        Math.floor(new Date(endDate).getTime() / 1000)
                    ]
                };
            }

            if (params.page) {
                page = parseInt(params.page, 10);
            }
            if (params.pageSize) {
                pageSize = parseInt(params.pageSize, 10);
            }
        }

        const offset = (page - 1) * pageSize;
        const limit = pageSize;

        const { count, rows } = await Order.findAndCountAll({
            where: where,
            attributes: [
                'id',
                'order_no',
                'user_id',
                'total_amount',
                'deposit_amount',
                'payment_method_type',
                'order_status',
                'rent_start_date',
                'rent_end_date',
                'actual_rent_days',
                'delivery_address',
                'product_id',
                'quantity',
                'item_deposit',
                'user_notes',
                'cancel_reason',
                'created_at',
                'updated_at'
            ],
            offset: offset,
            limit: limit,
            order: [['created_at', 'DESC']]
        });

        return {
            total: count,
            list: rows,
            page: page,
            pageSize: pageSize
        };
    } catch (err) {
        throw new Error(`Error in getAllOrders: ${err.message}`);
    }
};

module.exports = {
    getAllOrders
};
